package com.ruoyi.task.service.impl;



import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.RoleConstants;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.enums.RoleIdEnum;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.task.domain.TaskMediaResp;
import com.ruoyi.task.domain.entity.DataTaskEntity;
import com.ruoyi.task.mapper.DataTaskMapper;
import com.ruoyi.task.service.IDataTaskService;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Future;
import java.util.stream.Collectors;



/**
 * 测试任务Service业务层处理
 */
@Service
public class DataTaskServiceImpl implements IDataTaskService {

    @Resource
    private DataTaskMapper dataTaskMapper;

    @Resource
    private ISysDictDataService dictDataService;



    /**
     * 根据ID测试测试任务
     *
     * @param dataTaskId
     * @return
     */
    @Async("threadPoolKy")
    @Override
    public Future<DataTaskEntity> selectDataTask(Long dataTaskId) {
        DataTaskEntity dataTaskEntity = dataTaskMapper.selectDataTaskByDataTaskId(dataTaskId);
        return new AsyncResult<>(dataTaskEntity);
    }

    /**
     * 查询测试任务
     *
     * @param dataTaskId 测试任务主键
     * @return 测试任务
     */
    @Override
    public DataTaskEntity selectDataTaskByDataTaskId(Long dataTaskId) {
        return dataTaskMapper.selectDataTaskByDataTaskId(dataTaskId);
    }

    /**
     * 查询测试任务列表
     *
     * @param dataTaskEntity 测试任务
     * @return 测试任务
     */
    @Override
    public List<DataTaskEntity> selectDataTaskList(DataTaskEntity dataTaskEntity) {
        return dataTaskMapper.selectDataTaskList(dataTaskEntity);
    }

    /**
     * 查询（”主检名称“ 或者 ”副检名称“ 是当前用户）测试任务列表
     *
     * @param dataTaskEntity 测试任务
     * @return 测试任务集合
     */
    @Override
    public List<DataTaskEntity> selectDataTaskListForUserName(DataTaskEntity dataTaskEntity) {
        return dataTaskMapper.selectDataTaskListForUserName(dataTaskEntity);
    }


    /**
     * 查询（本部门及以下的任务）测试任务列表
     *
     * @param dataTaskEntity
     * @return
     */
    @Override
    public List<DataTaskEntity> selectDataTaskListForDeptId(DataTaskEntity dataTaskEntity) {
        return dataTaskMapper.selectDataTaskListForDeptId(dataTaskEntity);
    }

    /**
     * 新增测试任务
     *
     * @param dataTaskEntity 测试任务
     * @return 结果
     */
    @Override
    public int insertDataTask(DataTaskEntity dataTaskEntity) {
        return dataTaskMapper.insertDataTask(dataTaskEntity);
    }

    /**
     * 修改测试任务
     *
     * @param dataTaskEntity 测试任务
     * @return 结果
     */
    @Override
    public int updateDataTask(DataTaskEntity dataTaskEntity) {
        dataTaskEntity.setUpdateTime(DateUtils.getNowDate());
        return dataTaskMapper.updateDataTask(dataTaskEntity);
    }

    /**
     * 批量删除测试任务
     *
     * @param dataTaskIds 需要删除的测试任务主键
     * @return 结果
     */
    @Override
    public int deleteDataTaskByDataTaskIds(Long[] dataTaskIds, String taskType) {
        // 设置 del_flag 为“2”
        return dataTaskMapper.updateByDataTaskIds(dataTaskIds);
    }


    @Override
    public List<DataTaskEntity> selectDataTaskListForDeptIdAndUserName(DataTaskEntity dataTaskEntity) {
        return dataTaskMapper.selectDataTaskListForDeptIdAndUserName(dataTaskEntity);
    }

    @Override
    public List<DataTaskEntity> selectDataTaskList(DataTaskEntity dataTaskEntity, boolean admin, boolean personal) {
        // 超级管理员
        // 个人用户
        // 企业拥有者、管理员、检测员
        if (admin || personal) {
            if (personal) {
                dataTaskEntity.setUserId(SecurityUtils.getLoginUser().getUser().getUserId());
            } else {
                dataTaskEntity.setUserName(null);
                dataTaskEntity.setUserId(null);
                dataTaskEntity.setDeptId(null);
            }
            // "超级管理员" 、 "个人用户"
            //startPage();
            List<DataTaskEntity> dataTaskEntities = selectDataTaskList(dataTaskEntity);
            return dataTaskEntities;
        } else {
            // 当前用户的角色信息
            List<SysRole> sysRoleEntityList = SecurityUtils.getLoginUser().getUser().getRoles();
            if (sysRoleEntityList != null && !sysRoleEntityList.isEmpty()) {
                // 角色信息
                List<String> roleKeyList = sysRoleEntityList.stream().map(SysRole::getRoleName).collect(Collectors.toList());
                // "企业拥有者"、"企业系统管理员"：本企业全部数据
                if (roleKeyList.contains(RoleConstants.ROLE_NAME_COMPANY_ACCOUNT_OWNER) || roleKeyList.contains(RoleConstants.ROLE_NAME_COMAPNY_ADMIN)) {
                    // 根据部门ID查询
                    dataTaskEntity.setDeptId(SecurityUtils.getLoginUser().getUser().getDeptId());
                    //startPage();
                    List<DataTaskEntity> dataTaskEntities = selectDataTaskListForDeptId(dataTaskEntity);
                    return dataTaskEntities;
                }else {
                    // TODO: 2023/8/25 注意此处的查询逻辑，部门ID不能为空
                    dataTaskEntity.setDeptId(SecurityUtils.getLoginUser().getUser().getDeptId());
                    // 其他人只查看自己
                    dataTaskEntity.setUserName(SecurityUtils.getLoginUser().getUser().getNickName());
                    //startPage();
                    List<DataTaskEntity> dataTaskEntities = selectDataTaskListForDeptIdAndUserName(dataTaskEntity);
                    return dataTaskEntities;
                }
//                // “检测员”：查询与自己相关的数据
//                if (roleKeyList.contains(RoleConstants.ROLE_NAME_INSPECTOR)) {
//
//                }
            }
        }
        return new ArrayList<>();
    }

    @Override
    public TaskMediaResp selectMedia(Long dataTaskId) {
        DataTaskEntity dataTaskEntity = dataTaskMapper.selectDataTaskByDataTaskId(dataTaskId);
        if (dataTaskEntity == null) {
            return null;
        }
        TaskMediaResp taskMediaRespDTO = new TaskMediaResp();
        List<String> imageUrlList = new ArrayList<>();
        List<String> imageScaleUrlList = new ArrayList<>();
        List<String> videoUrlList = new ArrayList<>();
        List<String> videoScaleUrlList = new ArrayList<>();
        String[] imgArray;
        String[] videoArray;
        if(null != dataTaskEntity.getImgNames()) {
            imgArray = dataTaskEntity.getImgNames().split("&");
            for (String s : imgArray) {
                imageUrlList.add(RuoYiConfig.getMediaPath() + "/" + s);
                imageScaleUrlList.add(RuoYiConfig.getMediaPath() + "/" + s.replace(".jpg", "-scale.jpg"));
            }
        }
        if(null != dataTaskEntity.getVideoNames()) {
            videoArray = dataTaskEntity.getVideoNames().split("&");
            for (String s : videoArray) {
                videoUrlList.add(RuoYiConfig.getMediaPath() + "/" + s);
                videoScaleUrlList.add(RuoYiConfig.getMediaPath() + "/" + s.replace(".mp4", "-scale.jpg"));
            }
        }
        taskMediaRespDTO.setImageUrlList(imageUrlList);
        taskMediaRespDTO.setImageScaleUrlList(imageScaleUrlList);
        taskMediaRespDTO.setVideoUrlList(videoUrlList);
        taskMediaRespDTO.setVideoScaleUrlList(videoScaleUrlList);
        return taskMediaRespDTO;
    }

    /**
     * 返回首页柱状图数据
     *
     * @param dateLength
     */
    @Override
    public List<Map<String, Object>> selectDataTaskByDate(Integer dateLength) {
        return dataTaskMapper.selectDataTaskByDate(dateLength);
    }

    /**
     * 根据任务类型返回首页柱状图数据
     *
     * @param startTime
     * @param endTime
     */
    @Override
    public List<Map<String, Object>> selectDataTaskByRangeDate(String startTime, String endTime) {
        return dataTaskMapper.selectDataTaskByRangeDate(startTime, endTime);
    }

}
